package com.bankcomm.ui.specialwidget;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;
import com.bankcomm.R;
import com.bankcomm.common.LPMid;
import com.bankcomm.ui.EMPView;
import com.rytong.tools.ui.Component;
import com.rytong.tools.ui.CssStyle;
import com.rytong.tools.utils.LPToastUtil;
import com.rytong.tools.utils.Utils;

public class LPButton extends Component {
    private static final int DEFAULT_BUTTON_UP_COLOR = 0xff346fbc;
    private static final int DEFAULT_BUTTON_DOWN_COLOR = 0xff000000;
    private static final int DEFAULT_BUTTON_FOCUS_COLOR = 0xffff0000;

    private String buttonType_; // submit/reset/cancel/button
    private boolean isNoCancel_ = false; // Indicate that this submit can not cancel

    boolean isRollNotStopB_ = false;

    private int textColor_;
    int clickedColor_;
    int clickedBgColor_;

    //密码键盘
    LPMid lpmid_ ;
   
    public static final String BTN_ACT_ADD = "add";
    public static final String BTN_ACT_DEL = "del";
    public static final String BTN_ACT_CONFIRM = "confirm";
    private String buttonAction_;
    private Drawable[] upDrawable_;
    private Drawable[] downDrawable_;
    private Drawable[] focusDrawable_;

    private Bitmap upButton_;
    private Bitmap downButton_;
    private Bitmap bgImg_;
    
    // 当前submit按钮被按下。
    public boolean isPressed_ = false;
    
    public class MyLPButton extends TextView implements CompositedComponent {

        public MyLPButton(Context context, String value) {
            super(context);
            // 设置控件文字显示内容为居�
            setGravity(Gravity.CENTER);
            setFocusable(true);
            setFocusableInTouchMode(true);
            setSingleLine(true);
            setEllipsize(TextUtils.TruncateAt.valueOf("END"));
            if(LPToastUtil.getInstance().isBranchBank){
            	setBackgroundResource(R.drawable.merchant_btn_selector);
            }
        }

        @Override
        public boolean onTouchEvent(MotionEvent event) {
            if (!isEnabled()) {
                return true;
            }
            boolean isAction = false;
            int touchEvent = event.getAction();
            switch (touchEvent) {
            case MotionEvent.ACTION_DOWN:
            	// 按下tr时候变色。
            	trDownColor(tr_, llvSV_);
            	// 向滚动视图中登记这个按钮，以便在滚动视图抢夺焦点的时候还原颜色。
            	if(Utils.sc_ != null){
            		Utils.sc_.currentButton_ = this.composited();
            	}
            	if(hs_ != null){
            		hs_.currentButton_ = this.composited();
            	}
            	if(vs_ != null){
            		vs_.currentButton_ = this.composited();
            	}
            	// 按下的时候改变按钮的背景图。
            	if(isEnabled() == true && downBG_ != -1){
            		setBackgroundResource(downBG_);
            	}
                setFocus(true);
                xDown_ = event.getX();
                yDown_ = event.getY();
                // requestFocus();
                invalidate();
                // 必须点击有效果，否则无法激活按钮的弹起效果
                isAction = true;
                break;
            case MotionEvent.ACTION_MOVE:
            	// 移动tr恢复颜色。
            	int offset = (int) Math.abs(yDown_ - event.getY());
            	if (offset > offset_) {
            		trMoveColor(tr_, llvSV_);
            		// 移动的时候恢复按钮的背景图。
            		if(isEnabled() == true && upBG_ != -1){
            			setBackgroundResource(upBG_);
            		}
            	}
                moveY(yDown_, event.getY());
                break;
            case MotionEvent.ACTION_UP:
            	// 抬起tr恢复颜色。
            	trUpColor(tr_, llvSV_);
            	// 向滚动视图中登记这个按钮，以便在滚动视图抢夺焦点的时候还原颜色。
            	if(Utils.sc_ != null){
            		Utils.sc_.currentButton_ = null;
            	}
            	if(hs_ != null){
            		hs_.currentButton_ = null;
            	}
            	if(vs_ != null){
            		vs_.currentButton_ = null;
            	}
            	// 抬起的时候恢复按钮的背景图。
            	if(isEnabled() == true && upBG_ != -1){
            		setBackgroundResource(upBG_);
            	}
                // 预防控件出现连击效果
//                long currentTime = System.currentTimeMillis();
//                long timedifference = currentTime - LASTCLICKTIME;
//                if (timedifference < 0) {
//                    LASTCLICKTIME = currentTime;
//                } else if (timedifference < jetLag_) {
//                    LASTCLICKTIME = currentTime;
//                    return false;
//                } else {
//                    LASTCLICKTIME = currentTime;
//                }
            	
            	isPressed_ = true;

                xUp_ = (int) event.getX();
                yUp_ = (int) event.getY();
                // 如果x或者y方向移动小于VALUE_个像素才判断为点击弹起，如果大于VALUE_个像素则判断为移动，不执行弹起效�
                if (Math.abs(xUp_ - xDown_) > offset_ || Math.abs(yUp_ - yDown_) > offset_) {
                    return false;
                }
                // 得到InputMethodManager的实例
                InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(
                        Context.INPUT_METHOD_SERVICE);
                // 对getCurrentFocus()做不为空判断，避免退出提示框上点击‘确定’和‘取消’按钮报空指针异�导致程序崩�
                if (null != imm && getActivity().getCurrentFocus() != null) {
                    // 关闭键盘
                    imm.hideSoftInputFromWindow(getActivity().getCurrentFocus().getApplicationWindowToken(),
                            InputMethodManager.HIDE_NOT_ALWAYS);

                }
                
                isAction = onClick((String) composited().property_.get("onclick"));
                
                String type = (String) getPropertyByName("type");
                if (null != type && type.equalsIgnoreCase("submit")) {
                	Utils.printOutToConsole("--------------------I Click Button----------------------");
                	((EMPView) LPButton.this.getActivity()).submit(LPButton.this);
                }
//                //密码键盘清空键值对
//                lpmid_ = LPMid.getInstance() ;
//                lpmid_.digitStr = null ;

                //isAction = onClick((String) composited().property_.get("onclick"));
                invalidate();
                break;
            default:
                isAction = super.onTouchEvent(event);
            }
            return isAction;
        }

        @Override
        public Component composited() {
            return LPButton.this;
        }

    }

    /**
     * @param buttonWidth
     * @param buttonHeight
     */
    private void createButton(int buttonWidth, Bitmap activeButton, Bitmap inactiveButton, Bitmap downButton) {
        try {
            focusImg_ = LPButton.makeButton(activeButton, buttonWidth);
        } catch (Exception ex) {
        }
    }

    /**
     * @return
     */
    private String searchButtonImgResId() {
        String resId = "";
        String imgName = null;
        CssStyle cssStyle = cssStyle();
        String bgImageUrl = (String) cssStyle.getProperty(CssStyle.BGIMAGEURL);
        if (cssStyle != null && bgImageUrl != null) {
            if (bgImageUrl.startsWith("local:")) {
                imgName = bgImageUrl.substring("local:".length());
                if (imgName.toLowerCase().startsWith("red")) {
                    resId = "button_all_red.png";
                } else if (imgName.equals("blueSButton.png")) {
                    resId = "button_small_blue.png";
                } else if (imgName.toLowerCase().startsWith("blue")) {
                    resId = "button_all_blue.png";
                }
            }
        }
        return resId;
    }

    /**
     * @param imgOri
     * @param width
     * @return
     * @throws Exception
     */
    public static Bitmap makeButton(Bitmap imgOri, int width) throws Exception {
        int ori_w = imgOri.getWidth();
        int ori_h = imgOri.getHeight();
        int[] ori_rgb = new int[ori_w * ori_h];
        int[] dst_rgb = new int[width * ori_h];

        int dst = 0;
        int src = 0;
        imgOri.getPixels(ori_rgb, 0, ori_w, 0, 0, ori_w, ori_h);

        int middle = width - ori_w;
        // Copy the first 6 columns from the ori image to the left border.
        for (int i = 0; i < ori_h; ++i) {
            if (i > 0) {
                src = i * ori_w;
            }
            for (int j = 0; j < ori_w; ++j) {
                dst_rgb[dst++] = ori_rgb[src++];
            }
            src -= 1;
            // Copy background from the 6-th column of the source image.
            for (int j = ori_w; j < middle; ++j) {
                dst_rgb[dst++] = ori_rgb[src];
            }
            // Copy the reverse of ori image to the right border.
            for (int j = middle; j < width; ++j) {
                dst_rgb[dst++] = ori_rgb[src--];
            }
        }
        Bitmap imgDst = null;
        imgDst = Bitmap.createBitmap(dst_rgb, width, ori_h, Bitmap.Config.ARGB_8888);
        return imgDst;
    }

    /**
     * @param buttonAction_
     *            the buttonAction_ to set
     */
    public void setButtonAction(String buttonAction_) {
        this.buttonAction_ = buttonAction_;
    }

    /**
     * @return the buttonAction_
     */
    public String buttonAction() {
        return buttonAction_;
    }

    /**
     * @param buttonType_
     *            the buttonType_ to set
     */
    public void setButtonType(String buttonType_) {
        this.buttonType_ = buttonType_;
    }

    /**
     * @return the buttonType_
     */
    public String buttonType() {
        return buttonType_;
    }

    /**
     * @param isNoCancel_
     *            the isNoCancel_ to set
     */
    public void setNoCancel(boolean isNoCancel_) {
        this.isNoCancel_ = isNoCancel_;
    }

    /**
     * @return the isNoCancel_
     */
    public boolean isNoCancel() {
        return isNoCancel_;
    }

    @Override
    public void initRealView(Activity activity, String value) {
        // TODO Auto-generated method stub
        realView_ = new MyLPButton(activity, value);
    }

    /**
     * 该方法主要用于指定控件的大小\显示颜色\样式�如果服务端没有给定输出样式大�则要自行计算一个合适的大小应用于该控�??Mould this component with its shape, color, size and
     * so on.
     * 
     * @return
     * @throws Exception
     *             TODO
     */
    public void mouldH() throws Exception {
        super.mouldH();
        setText(getPropertyByName("value"));
        String temp = getAttribute("BackgroundColor_");
        if (null != temp && !temp.equals("")) {
            int bgColor = Color.parseColor(temp);
            realView_.setBackgroundColor(bgColor);
        }
        if (null != cssStyle_) {
            mouldCssStyle();
        }
        // unFocusImg_指的是普通状态的按钮，由样式中的background-image确定；focusImg_指的是按下状态的按钮。
        getButtonStatusBG();
    }

    private void setText(String value) {
        // TODO Auto-generated method stub
        MyLPButton temp = (MyLPButton) realView_;
        temp.setText(value);
    }

    @Override
    public void mouldCssStyleByName(String name, String value) {
        super.mouldCssStyleByName(name, value);
        String temp = getAttribute("BackgroundColor_");
        if (cssStyle_ != null) {
            temp = cssStyle_.getProperty(CssStyle.BACKGROUNDCOLOR);
        }
//        if (null != temp && !temp.equals("")) {
//            int bgColor = Color.parseColor(temp);
//            realView_.setBackgroundColor(bgColor);
//        }
    }

    public void mouldCssStyle() {
        try {
            super.mouldCssStyle();
            MyLPButton mlpl = (MyLPButton) realView_;
            if (cssStyle_.getPropertyIndex(CssStyle.BGIMAGEURL) > cssStyle_.getPropertyIndex(CssStyle.BACKGROUNDCOLOR)) {

                String bgImageUrl = (String) cssStyle_.getProperty(CssStyle.BGIMAGEURL);

                if (null != bgImageUrl && !bgImageUrl.equals("")) {
                    // 根据样式定义控件选中图片
                    int index = bgImageUrl.indexOf(".");
                    String upButtonImageUrl = bgImageUrl.substring(0, index).concat("_copy.png");
                    upButton_ = Utils.getBitmapFromResources(getContext(), upButtonImageUrl);
                    if (upButton_ == null)
                        upButton_ = downButton_;
                    Bitmap disabledImg = Utils.getGrayBitmap(bgImg_);
                    if (isEnable()) {
                        mlpl.setBackgroundDrawable(new BitmapDrawable(unFocusImg_));
                    } else {
                        mlpl.setBackgroundDrawable(new BitmapDrawable(focusImg_));
                    }
                }
            } else {
                String temp = cssStyle_.getProperty(CssStyle.BACKGROUNDCOLOR);
                if (null != temp && !temp.equals("")) {
                    int bgColor = Color.parseColor(temp);
                    realView_.setBackgroundColor(bgColor);
                }
            }
        } catch (Exception e) {
            Utils.printException(e);
        }
    }
    
    @Override
    public void releaseResource(Component component) {
    	// TODO Auto-generated method stub
    	super.releaseResource(component);
    	Utils.releaseObject(upButton_);
        Utils.releaseObject(downButton_);
        Utils.releaseObject(bgImg_);
        if(null != upDrawable_){
        	if(upDrawable_.length > 0){
        		for(int i = 0;i < upDrawable_.length;i++){
        			Utils.releaseObject(upDrawable_[i]);
        		}        		
        	}
        	upDrawable_ = null;
        }
        
        if(null != downDrawable_){
        	if(downDrawable_.length > 0){
        		for(int i = 0;i < downDrawable_.length;i++){
        			Utils.releaseObject(downDrawable_[i]);
        		}        		
        	}
        	downDrawable_ = null;
        }
        
        if(null != focusDrawable_){
        	if(focusDrawable_.length > 0){
        		for(int i = 0;i < focusDrawable_.length;i++){
        			Utils.releaseObject(focusDrawable_[i]);
        		}        		
        	}
        	focusDrawable_ = null;
        }
    }
}